package yns.springboot.security.sample.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import yns.springboot.security.sample.dto.RoleDto;
import yns.springboot.security.sample.service.RoleService;
import yns.springboot.security.sample.utility.time.TimeUtility;





@RestController
@CrossOrigin
@RequestMapping("/role")
public class RoleController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private RoleService roleService;
	
	@GetMapping("/getRole")
//	@PreAuthorize("hasRole('ROLE_admin') OR hasRole('ROLE_common')")
	@PreAuthorize("hasAnyRole('ROLE_admin','ROLE_common')")
	public String getRole() {
		logger.info("getRole");

		List<RoleDto> list =  roleService.getRole();
		String result = JSON.toJSON(list).toString();

		return result;
	}

	@PostMapping("/addRole")
	public String addRole() {
		logger.info("addRole");
		
		//Test
		RoleDto roleDto = new RoleDto();
		roleDto.setRoleName("Test" + TimeUtility.getCurrentTime());
		
		int returnCode = roleService.addRole(roleDto);
		
		JSONObject result = new JSONObject();
		result.put("result", returnCode);
		
		logger.info("addRole : " + result);
		
		return result.toJSONString();
	}
}
